package com.example.demo.common.exception;

import com.example.demo.common.constant.StatusBusiness;
import com.example.demo.common.response.BaseResponse;
import com.example.demo.common.response.ResponseData;
import com.example.demo.util.common.ResponseDataUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.exceptions.PersistenceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;


/**
 * @description: 服务端异常统一处理
 * @author: GT
 * @create: 2020年4月24日16:02:09
 **/
@Slf4j
@RestControllerAdvice
public class CommonControllerExceptionConfig extends GlobalControllerException {
		/**
		 * 当前环境
		 */
		@Value("${spring.profiles.active}")
		private String profile;

		@ExceptionHandler({
				BusinessException.class
		})
		public ResponseData exceptionHandler(BusinessException e) {
			log.error(e.getMessage(), e);
			String msg = e.getMessage();
			BaseResponse baseResponse = new BaseResponse(e.getStatus(), msg);
			return ResponseDataUtil.baseResponseData(baseResponse);
		}

		@ExceptionHandler({
				MethodArgumentNotValidException.class
		})
		public ResponseData exceptionHandler(MethodArgumentNotValidException e) {
			String defaultMessage = e.getBindingResult().getFieldError().getDefaultMessage();
			log.error(defaultMessage, e);
			BaseResponse baseResponse = new BaseResponse(StatusBusiness.INVALIDATE.getStatus(), defaultMessage);
			return ResponseDataUtil.baseResponseData(baseResponse);
		}

		/**
		 * 帐号重复，新增失败，数据库报错拦截
		 **/
		@ExceptionHandler({
				DuplicateKeyException.class,
				DataAccessException.class
		})
		public ResponseData exceptionHandler(DataAccessException e) {
			log.error(e.getMessage(), e);
			String msg = "传入的数据重复或异常，操作失败！";
			BaseResponse baseResponse = new BaseResponse(StatusBusiness.INVALIDATE.getStatus(), msg);
			return ResponseDataUtil.baseResponseData(baseResponse);
		}

		/**
		 * 数据库操作异常
		 **/
		@ExceptionHandler({
				PersistenceException.class
		})
		public ResponseData exceptionHandler(PersistenceException e) {
			log.error(e.getMessage(), e);
			String msg = "传入的数据异常，操作失败！";
			BaseResponse baseResponse = new BaseResponse(StatusBusiness.INVALIDATE.getStatus(), msg);
			return ResponseDataUtil.baseResponseData(baseResponse);
		}

		@Override
		public void initEnv() {
			super.setProfile(profile);
		}
}

